<?php

require_once BASE_PATH . 'application/models/itemdao' . EXT;

class suscriptoresDAO extends baseDAO {

    var $table = "users";
    var $key = "id";

    function __construct() {
        // Call the Model constructor
        parent::__construct();
        $this->load->model('joomladao');
    }
    

    function findById($id) {
        $this->table = 'akeebasubs_subscriptions';
        $this->key = 'user_id';
        return $this->_findById($id);
    }

    function insertNewUser($data = array()) {
        if (count($data) > 0 && is_array($data)) {
            // Comprobar si Existe El Email en la base de datos
            $query = $this->db->get_where($this->table, array('email' => $data['email']));
            if ($query->num_rows() < 1) {

                $password = $this->joomladao->getCryptedPassword($data['pass']);
                // Insertar Datos Necesarios
                $a_array = array('name' => $data['name'],
                    'username' => strtolower($data['email']),
                    'email' => $data['email'],
                    'password' => $password,
                    'registerDate' => date('Y-m-d H:i:s'));
                $this->db->set($a_array);
                $this->db->insert($this->table);

                $b_array = array('user_id' => $this->db->insert_id(),
                    'group_id' => $this->getIdByTitleUserGroups('Subscribers'));
                $this->db->set($b_array);
                $this->db->insert('user_usergroup_map');

                return TRUE;
            }
            return FALSE;
        } else
            return FALSE;
    }

    function resetPassword($email, $password) {

        $password = $this->joomladao->getCryptedPassword($password);

        $this->db->set(array("password" => $password, "update" => 1));
        $this->db->where(array("email" => $email));
        $this->db->update($this->table);
    }

    function resetPasswordByid($id, $password) {

        $password = $this->joomladao->getCryptedPassword($password);

        $this->db->set(array("password" => $password, "update" => null));
        $this->db->where(array("id" => $id));
        if ($this->db->update($this->table))
            return TRUE;
        else
            return FALSE;
    }

    function genRandomString() {
        $length = 10;
        $characters = "0123456789abcdefghijklmnopqrstuvwxyz";
        $string = "";
        for ($p = 0; $p < $length; $p++) {
            $string .= $characters[mt_rand(0, strlen($characters) - 1)];
        }
        return $string;
    }

    function deleteUser($data = array()) {
        if (count($data) > 0 && is_array($data)) {
            // Validar los datos del usuario
            if (validateUser) {
                $this->db->select('id');
                $query = $this->db->get($this->table);
                $row = $query->row();
                $this->db->delete('user_usergroup_map', array('user_id' => $row->id));
                $this->db->delete($this->table, array('email' => $data['email']));

                return TRUE;
            }
            return FALSE;
        } else
            return FALSE;
    }

    function findUserByEmail($email) {
        $query = $this->db->get_where($this->table, array('email' => strtolower($email)));
        return $query->row();
    }

    function findUserByid($id) {
        $query = $this->db->get_where($this->table, array('id' => $id));
        return $query->row();
    }

    function findUserByEmailEnc($email) {
        $query = $this->db->get_where($this->table, array('md5(email)' => $email));
        return $query->row();
    }

    function getIdByTitleUserGroups($title) {
        $query = $this->db->get_where('usergroups', array('title' => $title));
        $row = $query->row();
        return $row->id;
    }

    function validateUser($data = array()) {

        $user = $this->findUserByEmail($data['email']);
        if (count($user) > 0) {
            $pass_array = explode(':', $user->password);

            if (count($pass_array) > 0) {
                $joomla_pass = $pass_array[0];
                $joomla_salt = $pass_array[1];

                if ($joomla_pass == md5($data['pass'] . $joomla_salt))
                    return TRUE;
                else
                    return FALSE;
            }else {
                if ($user->password == md5($data['pass']))
                    return TRUE;
                else
                    return FALSE;
            }
        }
    }

    function getLevelSuscription($data = array()) {

        $this->_sql($data);

        $result = $this->db->get('akeebasubs_levels');
        return $result->result();
    }

    function insertNewSuscriber($data = array()) {
        if (count($data) > 0 && is_array($data)) {
            // Comprobar si Existe El Email en la base de datos
            $this->load->model('sessionDAO');
            $usuario = $this->sessionDAO->getUser();
            // Insertar Datos Necesarios
            $a_array = array('user_id' => $usuario->id,
                'address1' => $data['address_street'],
                'city' => $data['address_city'],
                'state' => $data['address_state'],
                'zip' => $data['address_zip'],
                'country' => $data['address_country']);
            $this->db->set($a_array);
            $this->db->insert('akeebasubs_users');

            $cmd = $this->db->get_where('akeebasubs_levels', array('title' => $data['transaction_subject']));
            $cmd = $cmd->row();
            $b_array = array(
                'user_id' => $usuario->id,
                'akeebasubs_level_id' => $cmd->akeebasubs_level_id,
                'publish_up' => date('Y-m-d H:i:s'),
                'publish_down' => date("Y-m-d H:m:s", strtotime(date("Y-m-d H:m:s") . "+" . $cmd->duration . " day"))
            );

            $this->db->set($b_array);
            $this->db->insert('akeebasubs_subscriptions');

            return TRUE;
        } else
            return FALSE;
    }

    function getSuscriber() {
        $this->load->model('sessionDAO');
        $query = $this->sessionDAO->getUser();

        $result = $this->db->get_where('akeebasubs_subscriptions', array(
            'user_id' => @$query->id,
            'publish_down >=' => date('Y-m-d H:i:s'))
        );

        if ($result->num_rows() > 0)
            return TRUE;
        else
            return FALSE;
    }

}
